package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.PropertyInject;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.InjectType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class PropertyInjectAspect {
    private static final String CREATBY = "createBy";
    private static final String CREATETIME = "createTime";
    private static final String UPDATEBY = "updateBy";
    private static final String UPDATETIME = "updateTime";

    @Autowired
    private TokenService tokenService;

    @Pointcut("@annotation(com.ruoyi.common.annotation.PropertyInject)")
    public void propertyPointCut() {

    }

    @Before(value = "propertyPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) throws Throwable{
        Object[] args = joinPoint.getArgs();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String username = loginUser.getUsername();
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        PropertyInject propertyInject = signature.getMethod().getAnnotation(PropertyInject.class);
        InjectType type = propertyInject.type();
        if (StringUtils.isNotEmpty(args)) {
            for (Object arg : args) {
                BeanWrapperImpl wrapper = new BeanWrapperImpl(arg);
                if (wrapper.isWritableProperty(CREATBY)&&(type==InjectType.Insert||type==InjectType.Insert_Update)) {
                    wrapper.setPropertyValue(CREATBY, username);
                }
                if (wrapper.isWritableProperty(CREATETIME)&&(type==InjectType.Insert||type==InjectType.Insert_Update)) {
                    wrapper.setPropertyValue(CREATETIME, DateUtils.getNowDate());
                }
                if (wrapper.isWritableProperty(UPDATEBY)) {
                    wrapper.setPropertyValue(UPDATEBY, username);
                }
                if (wrapper.isWritableProperty(UPDATETIME)) {
                    wrapper.setPropertyValue(UPDATETIME, DateUtils.getNowDate());
                }
            }
        }

    }


}
